import { Subscription } from 'rxjs';
import { IPSAppCounterRef, IPSAppDataEntity, IPSAppDEField, IPSControl } from '@ibiz/dynamic-model-api';
import { LogUtil, ModelTool, Util } from '../../../util';
import { AppCtrlEventEngine, AppCustomEngine, AppTimerEngine } from '../../../engine';
import { AppModelService, GetModelService } from '../../../app';
import {
  IParam,
  IUIDataParam,
  IUIEnvironmentParam,
  IUIUtilParam,
  AppCtrlEvents,
  IAppCtrlHooks,
  IAppCtrlControllerBase,
  ICtrlActionResult,
  ILoadingService,
  IUIService,
  IEntityService,
} from '../../../interface';
import { AppCtrlHooks } from '../../hooks';
import { AppViewLogicUtil } from '../../utils';
import { AppUIControllerBase } from '../base';

export class AppCtrlControllerBase extends AppUIControllerBase implements IAppCtrlControllerBase {
  /**
   * @description 原生引用控件名称
   * @type {string}
   * @memberof AppCtrlControllerBase
   */
  public realCtrlRefName: string = '';

  /**
   * @description 视图钩子对象
   * @type {IAppCtrlHooks}
   * @memberof AppCtrlControllerBase
   */
  public hooks: IAppCtrlHooks = new AppCtrlHooks();

  /**
   * @description 部件模型实例对象
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public controlInstance!: any;

  /**
   * @description 名称
   * @type {string}
   * @memberof AppCtrlControllerBase
   */
  public name!: string;

  /**
   * @description 部件类型
   * @type {string}
   * @memberof AppCtrlControllerBase
   */
  public ctrlType!: string;

  /**
   * @description 部件显示模式
   * @type {string}
   * @memberof AppCtrlControllerBase
   */
  public ctrlShowMode!: string;

  /**
   * @description 部件样式
   * @type {string}
   * @memberof AppCtrlControllerBase
   */
  public ctrlStyle!: string;

  /**
   * @description 视图通讯对象
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public viewState: any;

  /**
   * @description 应用上下文
   * @type {IParam}
   * @memberof AppCtrlControllerBase
   */
  public context: IParam = {};

  /**
   * @description 视图参数
   * @type {IParam}
   * @memberof AppCtrlControllerBase
   */
  public viewParam: IParam = {};

  /**
   * @description 模型数据是否加载完成
   * @type {boolean}
   * @memberof AppCtrlControllerBase
   */
  public controlIsLoaded: boolean = false;

  /**
   * @description 模型服务
   * @type {AppModelService}
   * @memberof AppCtrlControllerBase
   */
  public modelService!: AppModelService;

  /**
   * @description 部件服务对象
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public ctrlService: any;

  /**
   * @description 应用数据服务对象
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public appDataService!: IEntityService;

  /**
   * @description 应用界面服务对象
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public appUIService!: IUIService;

  /**
   * @description 计数器服务对象集合
   * @type {Array<any>}
   * @memberof AppCtrlControllerBase
   */
  public counterServiceArray: Array<any> = [];

  /**
   * @description 视图计数器服务数组
   * @type {IParam[]}
   * @memberof AppCtrlControllerBase
   */
  public viewCounterServiceArray: IParam[] = [];

  /**
   * @description 外部传入数据对象
   * @type {Array<IParam>}
   * @memberof AppCtrlControllerBase
   */
  public navDatas: Array<IParam> = [];

  /**
   * @description 视图操作参数集合
   * @type {IUIUtilParam}
   * @memberof AppCtrlControllerBase
   */
  public viewCtx!: IUIUtilParam;

  /**
   * @description 界面触发逻辑Map
   * @type {Map<string, any>}
   * @memberof AppCtrlControllerBase
   */
  public ctrlTriggerLogicMap: Map<string, any> = new Map();

  /**
   * @description 原生界面触发逻辑集合
   * @type {Array<any>}
   * @memberof AppCtrlControllerBase
   */
  public realCtrlTriggerLogicArray: Array<any> = [];

  /**
   * @description 订阅视图状态事件
   * @type {(Subscription | undefined)}
   * @memberof AppCtrlControllerBase
   */
  public viewStateEvent: Subscription | undefined;

  /**
   * @description 挂载状态集合
   * @type {Map<string, boolean>}
   * @memberof AppCtrlControllerBase
   */
  public mountedMap: Map<string, boolean> = new Map();

  /**
   * @description 部件引用控制器集合
   * @type {Map<string, IParam>}
   * @memberof AppCtrlControllerBase
   */
  public ctrlRefsMap: Map<string, IParam> = new Map();

  /**
   * @description 是否部件已经完成
   * @type {boolean}
   * @memberof AppCtrlControllerBase
   */
  public hasCtrlMounted: boolean = false;

  /**
   * @description 显示处理提示
   * @type {boolean}
   * @memberof AppCtrlControllerBase
   */
  public showBusyIndicator: boolean = true;

  /**
   * @description 部件行为--load
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public loadAction: any;

  /**
   * @description 部件行为--loaddraft
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public loaddraftAction: any;

  /**
   * @description 部件行为--create
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public createAction?: any;

  /**
   * @description 部件行为--remove
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public removeAction: any;

  /**
   * @description 部件行为--update
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public updateAction: any;

  /**
   * @description 部件行为--submit
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public WFSubmitAction?: any;

  /**
   * @description 部件行为--start
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public WFStartAction?: any;

  /**
   * @description 界面行为模型
   * @type {IParam}
   * @memberof AppCtrlControllerBase
   */
  public actionModel: IParam = {};

  /**
   * @description 部件加载服务
   * @type {ILoadingService}
   * @memberof AppCtrlControllerBase
   */
  public ctrlLoadingService!: ILoadingService;

  /**
   * @description 应用状态事件
   * @type {(Subscription | undefined)}
   * @memberof AppCtrlControllerBase
   */
  public appStateEvent: Subscription | undefined;

  /**
   * @description 开启下拉刷新
   * @type {boolean}
   * @memberof AppCtrlControllerBase
   */
  public enablePullDownRefresh: boolean = false;

  /**
   * @description 部件UI是否存在权限
   * @type {boolean}
   * @memberof AppCtrlControllerBase
   */
  public enableControlUIAuth: boolean = true;

  /**
   * @description 预览数据
   * @type {*}
   * @memberof AppCtrlControllerBase
   */
  public previewData: IParam[] = [];

  /**
   * @description 应用实体codeName
   * @readonly
   * @memberof AppCtrlControllerBase
   */
  get appDeCodeName() {
    return this.controlInstance?.getPSAppDataEntity?.()?.codeName || '';
  }

  /**
   * @description 应用实体映射实体名称
   * @readonly
   * @memberof AppCtrlControllerBase
   */
  get deName() {
    return this.controlInstance?.getPSAppDataEntity()?.getPSDEName() || '';
  }

  /**
   * @description 应用实体主键属性codeName
   * @readonly
   * @memberof AppCtrlControllerBase
   */
  get appDeKeyFieldName() {
    return (
      (ModelTool.getAppEntityKeyField(this.controlInstance?.getPSAppDataEntity() as IPSAppDataEntity) as IPSAppDEField)
        ?.codeName || ''
    );
  }

  /**
   * @description 应用实体主信息属性codeName
   * @readonly
   * @memberof AppCtrlControllerBase
   */
  get appDeMajorFieldName() {
    return (
      (
        ModelTool.getAppEntityMajorField(
          this.controlInstance?.getPSAppDataEntity() as IPSAppDataEntity,
        ) as IPSAppDEField
      )?.codeName || ''
    );
  }

  /**
   * Creates an instance of AppCtrlControllerBase.
   * @param {*} opts 构建参数
   * @memberof AppCtrlControllerBase
   */
  public constructor(opts: any) {
    super(opts);
    this.initInputData(opts);
  }

  /**
   * @description 初始化输入数据
   * @param {IParam} opts 输入参数
   * @memberof AppCtrlControllerBase
   */
  public initInputData(opts: IParam) {
    this.viewState = opts.viewState;
    this.context = opts.navContext;
    this.viewParam = opts.navParam;
    this.viewCtx = opts.viewCtx;
    this.navDatas = opts.navDatas ? opts.navDatas : [];
    this.previewData = opts.previewData;
    if (App.isPreviewMode() && opts.modelData) {
      this.controlInstance = opts.modelData;
    } else {
      this.controlInstance = opts.controlInstance;
    }
    this.modelService = opts.modelService;
    this.viewCounterServiceArray = opts.viewCounterServiceArray;
    this.ctrlShowMode = opts.ctrlShowMode ? opts.ctrlShowMode : 'DEFAULT';
    this.enablePullDownRefresh = opts.enablePullDownRefresh ? opts.enablePullDownRefresh : false;
  }

  /**
   * @description 部件初始化
   * @return {*}  {Promise<boolean>}
   * @memberof AppCtrlControllerBase
   */
  public async controlInit(): Promise<boolean> {
    await this.ctrlModelInit();
    this.hooks.modelLoaded.callSync({ arg: this.controlInstance });
    this.ctrlInit();
    this.controlIsLoaded = true;
    setTimeout(() => {
      this.setIsMounted();
    }, 0);
    // 全局刷新通知
    if (App.isPreviewMode()) {
      return this.controlIsLoaded;
    }
    if (App.getCenterService().getMessageCenter()) {
      this.appStateEvent = App.getCenterService()
        .getMessageCenter()
        .subscribe(({ name, action, data }: { name: string; action: string; data: any }) => {
          if (!this.appDeCodeName || !Object.is(name, this.appDeCodeName)) {
            return;
          }
          if (Object.is(action, 'appRefresh')) {
            this.refresh(data);
          }
        });
    }
    return this.controlIsLoaded;
  }

  /**
   * @description 初始化实体服务对象
   * @memberof AppCtrlControllerBase
   */
  public async initAppDataService() {
    if (App.isPreviewMode()) {
      return;
    }
    const appDataEntity = this.controlInstance?.getPSAppDataEntity?.();
    this.appDataService = await App.getEntityService().getService(
      this.context,
      appDataEntity?.codeName?.toLowerCase() || '',
    );
  }

  /**
   * @description 初始化应用界面服务对象
   * @memberof AppCtrlControllerBase
   */
  public async initAppUIService() {
    if (App.isPreviewMode()) {
      return;
    }
    const appDataEntity = this.controlInstance?.getPSAppDataEntity?.();
    this.appUIService = await App.getUIService().getService(this.context, appDataEntity?.codeName?.toLowerCase() || '');
    if (this.appUIService) {
      await this.appUIService.loaded();
    }
  }

  /**
   * @description 计数器刷新
   * @memberof AppCtrlControllerBase
   */
  public counterRefresh() {
    if (this.counterServiceArray && this.counterServiceArray.length > 0) {
      this.counterServiceArray.forEach((item: any) => {
        const counterService = item.service;
        if (
          counterService &&
          counterService.refreshCounterData &&
          counterService.refreshCounterData instanceof Function
        ) {
          counterService.refreshCounterData(this.context, this.viewParam);
        }
      });
    }
  }

  /**
   * @description 部件销毁
   * @memberof AppCtrlControllerBase
   */
  public async controlDestroy() {
    if (this.viewStateEvent) {
      this.viewStateEvent.unsubscribe();
    }
    // 销毁计数器定时器
    if (this.counterServiceArray && this.counterServiceArray.length > 0) {
      this.counterServiceArray.forEach((item: any) => {
        const counterService = item.service;
        if (counterService && counterService.destroyCounter && counterService.destroyCounter instanceof Function) {
          counterService.destroyCounter();
        }
      });
    }
    // 销毁部件定时器逻辑
    this.destroyLogicTimer();
    if (this.appStateEvent) {
      this.appStateEvent.unsubscribe();
    }
    this.cancelSubscribe();
  }

  /**
   * @description 获取部件类型
   * @return {*}  {string}
   * @memberof AppCtrlControllerBase
   */
  public getControlType(): string {
    return this.controlInstance.controlType;
  }

  /**
   * @description 获取多项数据
   * @return {*}  {any[]}
   * @memberof AppCtrlControllerBase
   */
  public getDatas(): any[] {
    return [];
  }

  /**
   * @description 获取单项数据
   * @return {*}  {*}
   * @memberof AppCtrlControllerBase
   */
  public getData(): any {
    return null;
  }

  /**
   * @description 获取计数器服务
   * @param {IPSAppCounterRef} [appCounterRef] 计数器引用
   * @return {*}
   * @memberof AppCtrlControllerBase
   */
  public getCounterService(appCounterRef?: IPSAppCounterRef) {
    if (appCounterRef) {
      return Util.findElementByField(this.counterServiceArray, 'id', appCounterRef.id)?.service;
    } else if (this.viewCounterServiceArray?.length > 0) {
      return this.viewCounterServiceArray[0].service;
    } else {
      return null;
    }
  }

  /**
   * @description 获取逻辑UI数据
   * @return {*}  {IUIDataParam}
   * @memberof AppCtrlControllerBase
   */
  public getUIDataParam(): IUIDataParam {
    return {
      data: this.getDatas(),
      navContext: this.context,
      navParam: this.viewParam,
      navData: this.navDatas,
      sender: this,
    };
  }

  /**
   * @description 获取逻辑环境数据
   * @return {*}  {IUIEnvironmentParam}
   * @memberof AppCtrlControllerBase
   */
  public getUIEnvironmentParam(): IUIEnvironmentParam {
    return {
      app: this.viewCtx?.app,
      view: this.viewCtx?.view,
      ctrl: this,
      parentDeCodeName: null,
    };
  }

  /**
   * @description 初始化挂载状态集合
   * @memberof AppCtrlControllerBase
   */
  public initMountedMap() {
    const controls = this.controlInstance?.getPSControls?.();
    controls?.forEach((item: any) => {
      if (item.controlType == 'CONTEXTMENU' || item.controlType == 'TOOLBAR') {
        this.mountedMap.set(item.name, true);
      } else {
        this.mountedMap.set(item.name, false);
      }
    });
    this.mountedMap.set('self', false);
  }

  /**
   * @description 设置已经绘制完成状态
   * @param {string} [name='self'] 部件类型名
   * @param {*} [data] 数据
   * @memberof AppCtrlControllerBase
   */
  public setIsMounted(name: string = 'self', data?: any) {
    this.mountedMap.set(name, true);
    if (data) {
      this.ctrlRefsMap.set(name, data);
    }
    if ([...this.mountedMap.values()].indexOf(false) == -1) {
      // 执行ctrlMounted
      if (!this.hasCtrlMounted) {
        this.ctrlMounted();
      }
    }
  }

  /**
   * @description 部件挂载
   * @param {*} [args] 挂载参数
   * @memberof AppCtrlControllerBase
   */
  public ctrlMounted(args?: any) {
    this.hasCtrlMounted = true;
    this.ctrlEvent(AppCtrlEvents.MOUNTED, this);
    this.hooks.mounted.callSync({ arg: this })
    if (this.realCtrlRefName && this.realCtrlTriggerLogicArray.length > 0) {
      // TODO 原生事件
      // let timer: any = setInterval(() => {
      //   if (this.$refs && this.$refs[this.realCtrlRefName]) {
      //     clearInterval(timer);
      //     for (const item of this.realCtrlTriggerLogicArray) {
      //       (this.$refs[this.realCtrlRefName] as Vue).$on(item, (...args: any) => {
      //         this.handleRealCtrlEvent(item, this.getData(), args);
      //       });
      //     }
      //   }
      // }, 100);
    }
  }

  /**
   * @description 部件模型数据加载
   * @memberof AppCtrlControllerBase
   */
  public async ctrlModelLoad() {
    if (App.isPreviewMode()) {
      return ;
    }
    // 部件存在应用实体加载
    if (this.controlInstance?.getPSAppDataEntity?.()) {
      const AppDataEntity = this.controlInstance.getPSAppDataEntity();
      await AppDataEntity.fill(true);
    }
    // 部件子部件数据加载
    if (this.controlInstance?.getPSControls?.()) {
      for (const control of this.controlInstance.getPSControls() as IPSControl[]) {
        await control.fill(true);
      }
    }
  }

  /**
   * @description 初始化计数器服务
   * @return {*}
   * @memberof AppCtrlControllerBase
   */
  public async initCounterService() {
    if (!this.controlInstance || App.isPreviewMode()) {
      return;
    }
    const appCounterRef: Array<IPSAppCounterRef> = this.controlInstance.getPSAppCounterRefs?.() || [];
    if (appCounterRef && appCounterRef.length > 0) {
      for (const counterRef of appCounterRef) {
        const counter = counterRef.getPSAppCounter?.();
        if (counter) {
          await counter.fill(true);
          const counterService = App.getCounterService();
          await counterService.loaded(counter, { navContext: this.context, navViewParam: this.viewParam });
          const tempData: any = { id: counterRef.id, path: counter.modelPath, service: counterService };
          this.counterServiceArray.push(tempData);
        }
      }
    }
  }

  /**
   * @description 初始化部件逻辑
   * @memberof AppCtrlControllerBase
   */
  public async initControlLogic() {
    if (
      this.controlInstance &&
      this.controlInstance.getPSControlLogics() &&
      this.controlInstance.getPSControlLogics().length > 0
    ) {
      this.realCtrlTriggerLogicArray = [];
      this.controlInstance.getPSControlLogics().forEach((element: any) => {
        // 目标逻辑类型类型为实体界面逻辑、系统预置界面逻辑、前端扩展插件、脚本代码
        if (
          element &&
          element.triggerType &&
          (Object.is(element.logicType, 'DEUILOGIC') ||
            Object.is(element.logicType, 'SYSVIEWLOGIC') ||
            Object.is(element.logicType, 'PFPLUGIN') ||
            Object.is(element.logicType, 'SCRIPT'))
        ) {
          switch (element.triggerType) {
            case 'CUSTOM':
              this.ctrlTriggerLogicMap.set(element.name.toLowerCase(), new AppCustomEngine(element));
              break;
            case 'CTRLEVENT':
              if (element.eventNames.startsWith('__')) {
                // 部件原生控件事件
                this.ctrlTriggerLogicMap.set(element.eventNames.toLowerCase(), new AppCtrlEventEngine(element));
              } else {
                if (element.eventNames.startsWith('_')) {
                  // 部件注册自定义事件
                  this.ctrlTriggerLogicMap.set(element.eventNames.toLowerCase(), new AppCtrlEventEngine(element));
                } else {
                  // 部件内置事件
                  this.ctrlTriggerLogicMap.set(element.eventNames.toLowerCase(), new AppCtrlEventEngine(element));
                }
              }
              break;
            case 'TIMER':
              this.ctrlTriggerLogicMap.set(element.name.toLowerCase(), new AppTimerEngine(element));
              break;
            default:
              LogUtil.log(`${element.triggerType}类型暂未支持`);
              break;
          }
        }
        // 初始化原生界面触发逻辑
        if (element.eventNames && element.eventNames.startsWith('__')) {
          const eventNames = element.eventNames.slice('__'.length);
          this.realCtrlTriggerLogicArray.push(eventNames);
        }
        // 绑定用户自定义事件
        if (element.eventNames && element.eventNames.startsWith('_') && !element.eventNames.startsWith('__')) {
          const eventName = element.eventNames.toLowerCase().slice(1);
          this.on(eventName, (...args: any) => {
            this.handleCtrlCustomEvent(element.eventNames.toLowerCase(), this.getData(), args);
          });
        }
      });
    }
  }

  /**
   * @description 部件模型数据初始化实例
   * @param {*} [args] 初始化参数
   * @memberof AppCtrlControllerBase
   */
  public async ctrlModelInit(args?: any) {
    await this.ctrlModelLoad();
    this.ctrlBasicInit();
    this.initMountedMap();
    await this.initAppDataService();
    await this.initAppUIService();
    await this.initCounterService();
    await this.initControlLogic();
  }

  /**
   * @description 部件初始化
   * @param {*} [args] 初始化参数
   * @memberof AppCtrlControllerBase
   */
  public ctrlInit(args?: any) {
    if (this.viewState) {
      this.viewStateEvent = this.viewState.subscribe(
        ({ tag, action, data }: { tag: string; action: string; data: any }) => {
          if (!Object.is(tag, this.name)) {
            return;
          }
          if (Object.is('reset', action)) {
            this.onReset();
          }
          if (Object.is('save', action)) {
            if (this.save && this.save instanceof Function) {
              this.save(data);
            } else {
              this.ctrlEvent('save', null);
            }
          }
          if (Object.is('refresh', action)) {
            if (this.refresh && this.refresh instanceof Function) {
              this.refresh(data);
            }
          }
        },
      );
    }
    // 处理部件定时器逻辑
    this.handleTimerLogic();
  }

  /**
   * @description 部件基础数据初始化
   * @memberof AppCtrlControllerBase
   */
  public ctrlBasicInit() {
    this.name = this.controlInstance.name ? this.controlInstance.name : this.controlInstance.codeName;
    this.ctrlType = this.controlInstance.controlType;
    this.ctrlStyle = this.controlInstance.controlStyle ? this.controlInstance.controlStyle : 'DEFAULT';
    this.initActions();
    this.initCtrlActionModel();
    if (!App.isPreviewMode()) {
      this.ctrlLoadingService = App.getLoadingService();
    }
  }

  /**
   * @description 初始化实体行为
   * @memberof AppCtrlControllerBase
   */
  public initActions() {
    this.loadAction = this.controlInstance.getGetPSControlAction?.()?.actionName;
    this.loaddraftAction = this.controlInstance.getGetDraftPSControlAction?.()?.actionName || 'GetDraft';
    this.updateAction = this.controlInstance.getUpdatePSControlAction?.()?.actionName;
    this.removeAction = this.controlInstance.getRemovePSControlAction?.()?.actionName;
    this.loadAction = this.controlInstance.getGetPSControlAction?.()?.actionName;
    this.createAction = this.controlInstance.getCreatePSControlAction?.()?.actionName;
    this.WFSubmitAction = this.controlInstance.getWFSubmitPSControlAction?.()?.actionName;
    this.WFStartAction = this.controlInstance.getWFStartPSControlAction?.()?.actionName;
  }

  /**
   * @description 初始化界面行为模型
   * @memberof AppCtrlControllerBase
   */
  public initCtrlActionModel() {}

  /**
   * @description 重置
   * @memberof AppCtrlControllerBase
   */
  public onReset() {
    App.getNoticeService().warning(`${this.controlInstance.name}重置功能暂未实现`);
  }

  /**
   * @description 转化数据
   * @param {*} args
   * @memberof AppCtrlControllerBase
   */
  public transformData(args: any) {}

  /**
   * @description 开始加载
   * @memberof AppCtrlControllerBase
   */
  public ctrlBeginLoading() {
    this.ctrlLoadingService.beginLoading();
  }

  /**
   * @description 结束加载
   * @memberof AppCtrlControllerBase
   */
  public ctrlEndLoading() {
    this.ctrlLoadingService.endLoading();
  }

  /**
   * @description 保存
   * @memberof AppCtrlControllerBase
   */
  public save(data: IParam) {}

  /**
   * 处理部件UI请求
   *
   * @param {string} action 行为名称
   * @param {*} context 上下文
   * @param {*} viewparam 视图参数
   * @param {boolean} loadding 是否显示加载遮罩
   * @memberof AppCtrlControllerBase
   */
  /**
   * @description 处理部件UI请求
   * @param {string} action 行为
   * @param {*} context 上下文
   * @param {*} viewParam 视图参数
   * @param {boolean} [loadding=true] 是否显示loadding效果
   * @memberof AppCtrlControllerBase
   */
  public onControlRequset(action: string, context: any, viewParam: any, loadding: boolean = true) {
    if (loadding) {
      this.ctrlBeginLoading();
    }
  }

  /**
   * @description 处理部件UI响应
   * @param {string} action 行为
   * @param {*} response 响应结果
   * @memberof AppCtrlControllerBase
   */
  public onControlResponse(action: string, response: any) {
    this.ctrlEndLoading();
    if (Object.is(action, 'load')) {
      this.controlIsLoaded = true;
    }
    if (response && response.status && response.status == 403) {
      // onAuthLimit
    }
  }

  /**
   * @description 下拉加载更多数据
   * @return {*}  {Promise<IParam>}
   * @memberof AppCtrlControllerBase
   */
  public async pullDownRefresh(): Promise<IParam> {
    if (this.refresh && this.refresh instanceof Function) {
      return await this.refresh();
    } else {
      return new Promise((resolve: any) => {
        resolve({ ret: false, data: null });
      });
    }
  }

  /**
   * @description 关闭视图
   * @param {*} args 关闭参数
   * @memberof AppCtrlControllerBase
   */
  public closeView(args: any): void {
    this.hooks.closeView.callSync({ arg: [args] });
  }

  /**
   * @description 刷新数据
   * @param {IParam} [opts] 行为参数
   * @param {IParam} [args] 额外参数
   * @param {boolean} [showInfo=true] 是否显示提示信息
   * @param {boolean} [loadding=true] 是否显示loadding效果
   * @return {*}  {Promise<ICtrlActionResult>}
   * @memberof AppCtrlControllerBase
   */
  public async refresh(
    opts?: IParam,
    args?: IParam,
    showInfo: boolean = true,
    loadding: boolean = true,
  ): Promise<ICtrlActionResult> {
    return Promise.resolve({ ret: false, data: null });
  }

  /**
   * @description 执行部件事件逻辑
   * @param {string} name 逻辑名称
   * @param {IUIDataParam} args { action: 行为名称, sender: 触发源对象，navContext: 导航上下文，navParam: 导航参数, navData: 导航数据, data: 源数据 }
   * @return {*}
   * @memberof AppCtrlControllerBase
   */
  public async executeCtrlEventLogic(name: string, args: IUIDataParam) {
    if (this.ctrlTriggerLogicMap.get(name.toLowerCase())) {
      await this.ctrlTriggerLogicMap
        .get(name.toLowerCase())
        .executeAsyncUILogic({ arg: args, utils: this.viewCtx, environments: this.getUIEnvironmentParam() });
      return args;
    }
  }

  /**
   * @description 处理控件自定义事件
   * @param {string} name 行为名称
   * @param {*} data 数据
   * @param {*} args 参数
   * @memberof AppCtrlControllerBase
   */
  public handleCtrlCustomEvent(name: string, data: any, args: any) {
    if (this.ctrlTriggerLogicMap.get(`${name}`)) {
      const tempUIDataParam: IUIDataParam = this.getUIDataParam();
      Object.assign(tempUIDataParam, { data: data, args: args });
      this.ctrlTriggerLogicMap
        .get(`${name}`)
        .executeAsyncUILogic({ arg: tempUIDataParam, utils: this.viewCtx, environments: this.getUIEnvironmentParam() });
    }
  }

  /**
   * @description 处理部件界面行为点击
   * @param {*} data 数据
   * @param {*} event 事件源
   * @param {*} detail 行为模型
   * @memberof AppCtrlControllerBase
   */
  public handleActionClick(data: IParam, event: MouseEvent, detail: IParam) {
    const { name } = this.controlInstance;
    const getPSAppViewLogics = this.controlInstance.getPSAppViewLogics();
    const UIDataParam: IUIDataParam = this.getUIDataParam();
    Object.assign(UIDataParam, { data: data, event: event });
    AppViewLogicUtil.executeViewLogic(
      `${name}_${detail.name}_click`,
      UIDataParam,
      this.getUIEnvironmentParam(),
      this.viewCtx,
      getPSAppViewLogics,
    );
  }

  /**
   * @description 处理部件定时器逻辑
   * @memberof AppCtrlControllerBase
   */
  public handleTimerLogic() {
    if (this.ctrlTriggerLogicMap && this.ctrlTriggerLogicMap.size > 0) {
      for (const item of this.ctrlTriggerLogicMap.values()) {
        if (item && item instanceof AppTimerEngine) {
          const tempUIDataParam: IUIDataParam = this.getUIDataParam();
          item.executeAsyncUILogic({
            arg: tempUIDataParam,
            utils: this.viewCtx,
            environments: this.getUIEnvironmentParam(),
          });
        }
      }
    }
  }

  /**
   * @description 销毁部件定时器逻辑
   * @memberof AppCtrlControllerBase
   */
  public destroyLogicTimer() {
    if (this.ctrlTriggerLogicMap && this.ctrlTriggerLogicMap.size > 0) {
      for (const item of this.ctrlTriggerLogicMap.values()) {
        if (item && item instanceof AppTimerEngine) {
          item.destroyTimer();
        }
      }
    }
  }

  /**
   * @description 部件事件 抛出
   * @param {string} action 抛出行为
   * @param {*} data 抛出数据
   * @memberof AppCtrlControllerBase
   */
  public ctrlEvent(action: string, data: any) {
    this.hooks.event.callSync({
      controlname: this.controlInstance.name,
      action: action,
      data: data,
    });
  }

  /**
   * @description 处理部件事件
   * @param {string} controlname 部件名称
   * @param {string} action 部件行为
   * @param {*} data 数据
   * @memberof AppCtrlControllerBase
   */
  public handleCtrlEvent(controlname: string, action: string, data: any) {
    switch (action) {
      case AppCtrlEvents.MOUNTED:
        this.setIsMounted(controlname, data);
        break;
      default:
        this.ctrlEvent(action, data);
        break;
    }
  }
}
